/* eslint-disable */
import Vue from 'vue'

// https://www.cnblogs.com/Lu-Lu/p/11168904.html

import {addResizeListener, removeResizeListener} from 'element-ui/src/utils/resize-event'

const doTableResize = (el, binding, vnode) => {
  const {componentInstance: $table} = vnode

  const {value} = binding

  if (!$table.height) {
    throw new Error("el-$table must set the height. Such as height='100px'")
  }
  const bottomOffset = (value && value.bottomOffset) || 50

  if (!$table) return
  const height = window.innerHeight - el.getBoundingClientRect().top - bottomOffset
  $table.layout.setHeight(height)
  // $table.store.updateColumns()
  // $table.doLayout()
}


const doDialogResize = (el, binding, vnode) => {
}


/**
 * 表格高度自适应，使用此功能必须先为表格设置初始值
 */
Vue.directive('table-height-adaptive', {
  bind(el, binding, vnode) {
    el.resizeListener = () => {
      el.$resize = true
      doTableResize(el, binding, vnode)
    }

    // addResizeListener(el, el.resizeListener)
    addResizeListener(window.document.body, el.resizeListener)
  },
  inserted(el, binding, vnode) {
    doTableResize(el, binding, vnode)
  },
  unbind(el) {
    // removeResizeListener(el, el.resizeListener)
    removeResizeListener(window.document.body, el.resizeListener)
  }
})

// 对话框拖动调节宽度
Vue.directive('dialog-drag-width', {
  bind(el, binding, vnode, oldVnode) {
    // 最外层的 dialog wrapper
    const wrapper = binding.value.wrapper.$el
    const defaultWidth = binding.value.defaultWidth
    const dragDom = wrapper.querySelector('.el-dialog') || wrapper

    // 设置split bar的样式
    el.style.position = 'absolute'
    el.style.top = '0px'
    el.style.left = '0px'
    el.style.width = '5px'
    el.style.height = (dragDom.offsetHeight - 2) + 'px'
    el.style.cursor = 'col-resize'
    el.style.opacity = '5'
    el.style.backgroundColor = 'transparent'

    // 给split bar添加图标
    let span = document.createElement('span')
    let li = document.createElement('li')
    li.style.position = 'absolute'
    li.style.top = '50%'
    li.style.left = '50%'
    li.setAttribute('class', 'fas fa-arrows-alt-h fas-lg')

    span.appendChild(li)
    el.appendChild(span)

    // 是否有自定义宽度
    let rawWidth = 0
    if (wrapper.style.width != '') {
      rawWidth = wrapper.style.width
    } else {
      rawWidth = defaultWidth
    }

    wrapper.style.width = '100%'
    let maxWidth = wrapper.offsetWidth
    wrapper.style.width = rawWidth


    // 计算出左边的距离
    let left = maxWidth - wrapper.offsetWidth
    wrapper.style.left = `${left}px`

    window.addEventListener('resize', (e) => {
      el.style.height = (dragDom.offsetHeight - 2) + 'px'

      // 记录原来的宽度 及 屏占比
      let oldWidth = wrapper.offsetWidth
      let oldWidthPercent = oldWidth / maxWidth * 1.0

      wrapper.style.width = '100%'
      maxWidth = wrapper.offsetWidth

      oldWidthPercent = oldWidthPercent > 100 ? 100 : oldWidthPercent

      // 设置left及width
      wrapper.style.left = (maxWidth - (maxWidth * oldWidthPercent)) + 'px'
      wrapper.style.width = `${maxWidth * oldWidthPercent}px`
    })


    el.onmousedown = (e1) => {
      // 当前点击时Left的值
      let offsetLeft = e1.clientX

      document.onmousemove = function (e) {
        e.preventDefault() // 移动时禁用默认事件

        if (offsetLeft == e.clientX) {
          return
        }

        // 移动的距离
        let moveDistance = offsetLeft - e.clientX

        wrapper.style.left = (wrapper.offsetLeft - moveDistance) + 'px'
        wrapper.style.width = (maxWidth - wrapper.offsetLeft) + 'px'

        // 已经拉到最左边了，最大化显示
        if (wrapper.offsetLeft <= 0) {
          wrapper.style.left = '0px'
          wrapper.style.width = maxWidth + 'px'
          return
        }

        // 已经拉到最右边了
        if (wrapper.offsetLeft >= (maxWidth - 50)) {
          wrapper.style.left = (maxWidth - 50) + 'px'
          wrapper.style.width = '50px'
          return
        }

        // 更新左边当前位置
        offsetLeft = e.clientX
      }

      document.onmouseup = function (e2) {
        document.onmousemove = null
        document.onmouseup = null
      }
    }
  }
})

/**
 * 监听鼠标滚动的指令
 */
// Vue.directive('scroll', {
//   // 当绑定元素插入到 DOM 中
//   inserted(el, binding) {
//     let callback = binding.value
//     el.addEventListener('mousewheel', (e) => {
//       if (callback) {
//         callback(el, e.deltaY)
//       }
//     })
//   }
// })

// Register a global custom directive called `v-focus`
Vue.directive('focus', {
  // When the bound element is inserted into the DOM...
  inserted(el) {
    // Focus the element
    el.focus()
  }
})


// v-dialogDrag: 弹窗拖拽属性
Vue.directive('dialog-drag', {
  bind(el, binding, vnode, oldVnode) {
    const dialogHeaderEl = el.querySelector('.el-dialog__header')
    const dragDom = el.querySelector('.el-dialog')
    //dialogHeaderEl.style.cursor = 'move';
    dialogHeaderEl.style.cssText += ';cursor:move;'
    dragDom.style.cssText += ';top:0px;'

    // 获取原有属性 ie dom元素.currentStyle 火狐谷歌 window.getComputedStyle(dom元素, null);
    const sty = (function() {
      if (window.document.currentStyle) {
        return (dom, attr) => dom.currentStyle[attr]
      } else {
        return (dom, attr) => getComputedStyle(dom, false)[attr]
      }
    })()

    dialogHeaderEl.onmousedown = e => {
      // 鼠标按下，计算当前元素距离可视区的距离
      const disX = e.clientX - dialogHeaderEl.offsetLeft
      const disY = e.clientY - dialogHeaderEl.offsetTop

      const screenWidth = document.body.clientWidth // body当前宽度
      const screenHeight = document.documentElement.clientHeight // 可见区域高度(应为body高度，可某些环境下无法获取)

      const dragDomWidth = dragDom.offsetWidth // 对话框宽度
      const dragDomheight = dragDom.offsetHeight // 对话框高度

      const minDragDomLeft = dragDom.offsetLeft
      const maxDragDomLeft = screenWidth - dragDom.offsetLeft - dragDomWidth

      const minDragDomTop = dragDom.offsetTop
      const maxDragDomTop = screenHeight - dragDom.offsetTop - dragDomheight

      // 获取到的值带px 正则匹配替换
      let styL = sty(dragDom, 'left')
      let styT = sty(dragDom, 'top')

      // 注意在ie中 第一次获取到的值为组件自带50% 移动之后赋值为px
      if (styL.includes('%')) {
        styL = +document.body.clientWidth * (+styL.replace(/\%/g, '') / 100)
        styT = +document.body.clientHeight * (+styT.replace(/\%/g, '') / 100)
      } else {
        styL = +styL.replace(/\px/g, '')
        styT = +styT.replace(/\px/g, '')
      }

      document.onmousemove = function(e) {
        // 通过事件委托，计算移动的距离
        let left = e.clientX - disX
        let top = e.clientY - disY

        // 边界处理
        if (-left > minDragDomLeft) {
          left = -minDragDomLeft
        } else if (left > maxDragDomLeft) {
          left = maxDragDomLeft
        }

        if (-top > minDragDomTop) {
          top = -minDragDomTop
        } else if (top > maxDragDomTop) {
          top = maxDragDomTop
        }

        // 移动当前元素
        dragDom.style.cssText += `;left:${left + styL}px;top:${top + styT}px;`
      }

      document.onmouseup = function(e) {
        document.onmousemove = null
        document.onmouseup = null
      }
    }
  }
})

// v-dialogDrag: 弹窗拖拽
Vue.directive('dialogDrag1', {
  bind(el, binding, vnode, oldVnode) {
    const dialogHeaderEl = el.querySelector('.el-dialog__header')
    const dragDom = el.querySelector('.el-dialog')
    dialogHeaderEl.style.cursor = 'move'

    // 获取原有属性 ie dom元素.currentStyle 火狐谷歌 window.getComputedStyle(dom元素, null);
    const sty = dragDom.currentStyle || window.getComputedStyle(dragDom, null)

    dialogHeaderEl.onmousedown = e => {
      // 鼠标按下，计算当前元素距离可视区的距离
      const disX = e.clientX - dialogHeaderEl.offsetLeft
      const disY = e.clientY - dialogHeaderEl.offsetTop

      // 获取到的值带px 正则匹配替换
      let styL, styT

      // 注意在ie中 第一次获取到的值为组件自带50% 移动之后赋值为px
      if (sty.left.includes('%')) {
        styL = +document.body.clientWidth * (+sty.left.replace(/\%/g, '') / 100)
        styT = +document.body.clientHeight * (+sty.top.replace(/\%/g, '') / 100)
      } else {
        styL = +sty.left.replace(/\px/g, '')
        styT = +sty.top.replace(/\px/g, '')
      }

      document.onmousemove = function(e) {
        // 通过事件委托，计算移动的距离
        const l = e.clientX - disX
        const t = e.clientY - disY

        // 移动当前元素
        let left = l + styL
        left = left < 0 ? 0 : left
        let top = t + styT
        top = top < 0 ? 0 : top

        dragDom.style.left = `${left}px`
        dragDom.style.top = `${top}px`

        //将此时的位置传出去
        //binding.value({x:e.pageX,y:e.pageY})
      }

      document.onmouseup = function(e) {
        document.onmousemove = null
        document.onmouseup = null
      }
    }
  }
})

// v-dialog-resize: 弹窗宽度拖大 拖小
Vue.directive('dialog-resize', {
  bind(el, binding, vnode, oldVnode) {

    Vue.nextTick(() => {
      const dragDom = el.querySelector('.el-dialog')
      // 设置split bar的样式
      let sizeEl = document.createElement('div')
      sizeEl.style.position = 'absolute'
      sizeEl.style.top = '0px'
      sizeEl.style.left = '0px'
      sizeEl.style.width = '5px'
      sizeEl.style.height = getComputedStyle(dragDom).height
      sizeEl.style.lineHeight = getComputedStyle(dragDom).height
      sizeEl.style.cursor = 'col-resize'
      sizeEl.style.opacity = '0.5'
      sizeEl.style.backgroundColor = 'transparent'
      sizeEl.style.lineHeight = '0px'

      // 给split bar添加图标
      let span = document.createElement('span')
      let li = document.createElement('li')
      li.style.position = 'absolute'
      li.style.top = '50%'
      li.style.left = '50%'
      li.setAttribute('class', 'fas fa-arrows-alt-h fas-lg')

      span.appendChild(li)
      sizeEl.appendChild(span)
      dragDom.appendChild(sizeEl)

      sizeEl.onmousedown = e => {
        // 鼠标按下，计算当前元素距离可视区的距离
        const anchorX0 = e.clientX
        const elX0 = getOffset(dragDom).X - el.offsetLeft
        const elW0 = dragDom.offsetWidth

        let anchorX = anchorX0
        let elX = elX0 + (anchorX0 - anchorX)
        let elW = elW0 + (anchorX0 - anchorX)
        document.onmousemove = function(e) {
          e.preventDefault() // 移动时禁用默认事件

          // 通过事件委托，计算移动的距离
          // const l = e.clientX - disX
          // dragDom.style.width = `${l}px`
          anchorX = e.clientX
          elX = elX0 - (anchorX0 - anchorX)
          elW = elW0 + (anchorX0 - anchorX)

          if (elX <= 0 || elW < elW0 / 3) return
          dragDom.style.cssText += `;left:${elX}px;width:${elW}px;`
        }
        document.onmouseup = function(e) {
          document.onmousemove = null
          document.onmouseup = null
        }
      }
    })


  }
})

function getOffset(elem){
  var actualLeft=elem.offsetLeft;
  var actualTop=elem.offsetTop;
  var father=elem.offsetParent;//返回父级节点
  while(father!=null){
    actualLeft+=father.offsetLeft;//父节点的坐标
    actualTop+=father.offsetTop;
    father=father.offsetParent;//如果父级还有父级
  }
  return {
    X:actualLeft,
    Y:actualTop
  }
}




Vue.directive('editable-row-focus-next-on-enter', {
  bind(el, {value}, vnode) {
    let {nextRow} = value

    el.addEventListener('keyup', (ev) => {
      if (ev.keyCode != 37 && ev.keyCode != 39) { //39:right 37:left 13:enter
        return
      }
      let activeElement = document.activeElement
      if (!activeElement) {
        return
      }
      let elements = el.querySelectorAll("el-input,input:not(:disabled),textarea:not(:disabled)");

      for (let i = 0; i < elements.length; i++) {
        let element = elements[i]
        if (element != activeElement) {
          continue
        }
        if (ev.keyCode == 39) {
          if (i + 2 >= elements.length) {
            // 最后一个文本框
            nextRow && nextRow()
            break
          }
          element = elements[i + 1]
        } 
        if (ev.keyCode == 37) {
          if (i < 1) {
            // 第一个
            nextRow && nextRow()
            break
          }
          element = elements[i - 1]
        }
        element.focus()
      }
    })
  }
})
